import * as types from '../../mutation-types'
import { apiGetRank } from '@/api/rank'
export default () => ({
  namespaced: true,
  state: {
    list: []
  },
  mutations: {
    [types.SET_RANK] (state, payload) {
      const { id, data } = payload
      const matchIndex = state.list.findIndex(item => item.id === id)
      if (matchIndex > -1) {
        state.list[matchIndex].data = data
      } else {
        state.list.push(payload)
      }      
    }
  },
  actions: {
    // 获取排行榜数据
    [types.GET_RANK] ({ commit, state }, { rid = 0 } = {}) {      
      return apiGetRank({ rid }).then(res => {
        const { data: { list }, code } = res
        if (code === 0) {          
          commit(`${types.SET_RANK}`, {
            id: rid,
            data: list
          })
          return list          
        } else {
          commit(`${types.SET_RANK}`, {
            id: rid,
            data: []
          })
          return []
        }
      })               
    },    
    // 服务端渲染模式下提前获取数据的方法
    asyncData({ dispatch }) {
      return Promise.all([
        dispatch(types.GET_RANK)
      ])
    }
  }
})
